﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.VirtualFileSystem;

namespace YDT.Payment.Application
{
    /// <summary>
    /// 微信本地支付
    /// </summary>
    public class WxNativePay : IWebPagePay
    {
        private readonly WxPayHttpClient _wxPayHttpClient;
        private const string nativeUrl = "https://api.mch.weixin.qq.com/v3/pay/transactions/native";// 支付接口
        private const string mchid = "1613333188"; // 商户Id
        private const string certpath = "/Pays/WxPay/certs/apiclient_cert.p12"; // 商户证书路径
        private const string certSerialNo = "60D277417D8BAC5586C7236B4A40565FE3F58F0F"; // 证书序列号

        public IVirtualFileProvider _virtualFileProvider { set; get; }

        public WxNativePay(WxPayHttpClient wxPayHttpClient)
        {
            _wxPayHttpClient = wxPayHttpClient;
        }

        /// <summary>
        /// 创建支付
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="orderSn"></param>
        /// <param name="totalPrice"></param>
        public WebPagePayResult CreatePay(string productName, string orderSn, string totalPrice)
        {
            // 1、创建支付对象
            NativePay nativePay = new NativePay();
            nativePay.description = productName;
            nativePay.out_trade_no = orderSn;
            nativePay.amount.total = int.Parse(float.Parse(totalPrice) * 100 + "");
            
            // 2、支付对象转换成json
            string nativePayJson = JsonConvert.SerializeObject(nativePay);

           string PhysicalPath = _virtualFileProvider.GetFileInfo(certpath).PhysicalPath;
            // 3、创建支付
            string result = _wxPayHttpClient.
                WeChatPostAsync(nativeUrl, 
                nativePayJson,
                PhysicalPath,
                mchid,
               certSerialNo).Result;

            // 4、支付结果反序列化
            WxNativePayResult wxNativePayResult = JsonConvert.DeserializeObject<WxNativePayResult>(result);

            // 5、结果转换
            WebPagePayResult  webPagePayResult = new WebPagePayResult();
            webPagePayResult.PayResult = wxNativePayResult.code_url;
            return webPagePayResult;
        }
    }
}
